<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px">
      <el-form-item label="护理计划名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入护理计划名称"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          style="width: 240px"
          clearable>
          <el-option
            v-for="dict in sys_nurse_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增护理计划 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="24" style="text-align: right">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:plan:add']"
          >新增护理计划</el-button
        >
      </el-col>
    </el-row>

    <!--护理计划列表展示区 -->
    <el-table v-loading="loading" :data="planList">
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="护理计划名称" align="center" prop="name" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <!-- 根据status的值，查找字典中对应的标签 -->
          <dict-tag :options="sys_nurse_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="danger"
            :disabled="scope.row.disable"
            @click="handleDelete(scope.row)"
            v-hasPermi="['service:plan:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            :disabled="scope.row.disable"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['service:plan:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleView(scope.row)"
            v-hasPermi="['service:plan:view']"
            >查看</el-button
          >
          <el-button
            link
            type="danger"
            :disabled="scope.row.disable"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['service:plan:stop']">
            {{ scope.row.status == 1 ? "停用" : "启用" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改护理计划对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        ref="planRef"
        :model="form"
        :rules="rules"
        label-width="130px"
        label-position="left">
        <el-form-item label="护理计划名称" prop="name">
          <el-input
            :disabled="viewDisable"
            v-model="form.name"
            placeholder="请输入护理计划名称"
            maxlength="10"
            show-word-limit
            style="width: 300px" />
        </el-form-item>
        <!-- 分割线 分割护理计划和护理项目信息 -->
        <el-divider content-position="center">护理项目信息</el-divider>
        <el-row :gutter="30" class="mb8">
          <el-col :span="1.5">
            <el-button
              :disabled="viewDisable"
              type="primary"
              icon="Plus"
              @click="handleAddCareItem"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              :disabled="viewDisable"
              type="danger"
              icon="Delete"
              @click="handleDeleteCareItem"
              >删除</el-button
            >
          </el-col>
        </el-row>

        <!-- 编辑框中护理项目内容展示 -->
        <el-table
          :data="carePlanItemList"
          :row-class-name="rowCareItemIndex"
          @selection-change="handleCareItemSelectionChange"
          size="large"
          ref="careItem">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="护理项目名称" prop="itemId" width="180">
            <template #default="scope">
              <el-select
                :disabled="viewDisable"
                v-model.number="scope.row.itemId"
                placeholder="请选择护理项目"
                filterable
                style="width: 160px">
                <el-option
                  v-for="item in careItemList"
                  :key="item.id"
                  :label="item.name"
                  :value="Number(item.id)" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 期望服务时间 -->
          <el-table-column label="期望服务时间" prop="executeTime" width="150">
            <template #default="scope">
              <el-time-picker
                :disabled="viewDisable"
                v-model="scope.row.executeTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择时间"
                style="width: 120px" />
            </template>
          </el-table-column>

          <!-- 执行周期 下拉框-->
          <el-table-column label="执行周期" prop="executionCycle" width="150">
            <template #default="scope">
              <el-select
                :disabled="viewDisable"
                v-model.number="scope.row.cycle"
                placeholder="请选择执行周期">
                <el-option
                  v-for="dict in sys_execute_cycle"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 执行频次 限制1-7次 -->
          <el-table-column label="执行频次()" prop="frequency" width="150">
            <template #default="scope">
              <el-input
                :disabled="viewDisable"
                v-model="scope.row.frequency"
                placeholder="请输入1-7"
                type="number"
                min="1"
                max="7"
                @input="validateFrequency(scope.row, scope.$index)"
                @blur="validateFrequency(scope.row, scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="viewDisable" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  changeStatus,
  listCareItem,
  getPlanIds,
} from "@/api/service/plan";

const { proxy } = getCurrentInstance();
const { sys_nurse_status, sys_execute_cycle } = proxy.useDict(
  "sys_nurse_status",
  "sys_execute_cycle"
);
//查询护理计划列表集合
const planList = ref([]);
//查询护理项目列表集合
const careItemList = ref([]);
//查询护理项目和计划的关联表集合
const carePlanItemList = ref([]);
//控制新增删除编辑框是否打开
const open = ref(false);
//控制护理计划列表展示区是否加载中
const loading = ref(true);
//搜索表单是否显示出来
const showSearch = ref(true);
const ids = ref([]);
//编辑框中选中的护理项目
const checkedCareItem = ref([]);
//分页插件查询总记录数
const total = ref(0);
//新增修改编辑框 标题
const title = ref("");
//护理等级关联的护理计划id集合
const planIds = ref([]);
//查询护理计划布尔值控制显示确定等按钮操作
const viewDisable = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
  },
  rules: {
    name: [
      { required: true, message: "护理计划名称不能为空", trigger: "blur" },
      { max: 10, message: "护理计划名称不能超过10个字符", trigger: "blur" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询护理计划列表 */
function getList() {
  loading.value = true;

  // 并发请求护理计划列表与已绑定计划ID，统一在数据就绪后处理
  Promise.all([listPlan(queryParams.value), getPlanIds()])
    .then(([planResponse, planIdsResponse]) => {
      // 护理计划列表与总数
      planList.value = planResponse.rows;
      total.value = planResponse.total;
      planIds.value = planIdsResponse.data || [];

      // 根据计划ID集合设置每项的禁用属性
      planList.value.forEach((item) => {
        const itemId = parseInt(item.id);
        if (planIds.value.includes(itemId)) {
          item.disable = true;
        } else {
          item.disable = false;
        }
      });
    })
    .catch((error) => {
      console.error("获取护理计划数据失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  viewDisable.value = false;
  reset();
}

// 表单重置
function reset() {
  //重新查询所有的护理项目
  listCareItem().then((response) => {
    careItemList.value = response.data;
  });
  //重置编辑删除框中的内容
  form.value = {
    id: null,
    code: null,
    sortOrder: null,
    name: null,
    status: null,
    createdAt: null,
    updatedAt: null,
    createdBy: null,
    updatedBy: null,
    remark: null,
    careItemId: null,
    extend2: null,
  };
  //重置护理项目和计划的关联表数组中的内容
  carePlanItemList.value = [];
  //重置表单输入框中的内容以及校验规则。 编辑对话框重置
  proxy.resetForm("planRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加护理计划";
}

/** 编辑修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  //根据id查询对应的护理计划
  getPlan(_id).then((response) => {
    form.value = response.data;
    carePlanItemList.value = response.data.carePlanItemList || [];
    open.value = true;
    title.value = "修改护理计划";
  });
}

/**查看的处理逻辑 */
function handleView(row) {
  reset();
  const _id = row.id || ids.value;
  //根据id查询对应的护理计划
  getPlan(_id).then((response) => {
    form.value = response.data;
    carePlanItemList.value = response.data.carePlanItemList || [];
    open.value = true;
    title.value = "查看护理计划";
  });
  viewDisable.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["planRef"].validate((valid) => {
    if (valid) {
      form.value.carePlanItemList = carePlanItemList.value;
      if (form.value.id != null) {
        updatePlan(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPlan(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除护理计划编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPlan(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 护理项目序号 */
function rowCareItemIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 护理计划项目的添加操作 */
function handleAddCareItem() {
  let obj = {};
  obj.planId = "";
  obj.itemId = "";
  obj.executeTime = "";
  obj.frequency = "";
  // obj.cycle = "";
  // obj.remark = "";
  // obj.createdBy = "";
  // obj.updatedBy = "";
  // obj.createAt = "";
  // obj.updateAt = "";
  carePlanItemList.value.push(obj);
}

/** 护理项目删除按钮操作 */
function handleDeleteCareItem() {
  if (checkedCareItem.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的护理项目数据");
  } else {
    const carePlanItems = carePlanItemList.value;
    //删除选中的护理项目 这里是一个序号集合
    const checkedCareItems = checkedCareItem.value;
    //过滤出未选中的护理项目，将其赋值给护理项目列表数组
    carePlanItemList.value = carePlanItems.filter(function (item) {
      return checkedCareItems.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleCareItemSelectionChange(selection) {
  //获取选中行  过滤出选中行的序号
  checkedCareItem.value = selection.map((item) => item.index);
}

/** 停用/启用护理计划 */
function handleChangeStatus(row) {
  const _id = row.id;
  proxy.$modal
    .confirm(
      "是否确认" +
        (row.status == 0 ? "启用" : "停用") +
        '护理计划编号为"' +
        _id +
        '"的数据项？'
    )
    .then(function () {
      return changeStatus(_id, row.status == 0 ? 1 : 0);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

/** 校验执行频次输入 */
function validateFrequency(row, index) {
  const frequency = row.frequency;
  
  // 如果为空，不进行校验
  if (!frequency) {
    return;
  }
  
  // 转换为数字
  const num = Number(frequency);
  
  // 校验是否为整数且在1-7范围内
  if (!Number.isInteger(num) || num < 1 || num > 7) {
    proxy.$modal.msgError("执行频次必须是1-7之间的整数");
    // 清空无效输入
    row.frequency = "";
    return;
  }
  
  // 确保存储的是整数
  row.frequency = num;
}

getList();
</script>
